<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="产品编码" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          placeholder="请输入产品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="BOM编码" prop="bomCode">
        <el-input
          v-model="queryParams.bomCode"
          placeholder="请输入BOM编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="BOM版本" prop="bomName">
        <el-input
          v-model="queryParams.bomName"
          placeholder="请输入BOM版本"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['md:excrete:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="excreteList" @selection-change="handleSelectionChange" border>
      <el-table-column label="拆解编码" align="center" prop="code">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['md:excrete:query']"
          >{{scope.row.code}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="产品物料编码" align="center" prop="itemCode" width="140" />
      <el-table-column label="产品物料名称" align="center" prop="itemName" :show-overflow-tooltip="true"/>
      <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true"/>
      <el-table-column label="单位" align="center" prop="unitOfMeasure" :show-overflow-tooltip="true"/>
      <el-table-column label="BOM编码" align="center" prop="bomCode" width="160" />
      <el-table-column label="BOM版本" align="center" prop="bomName" :show-overflow-tooltip="true"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status == '草稿' ? 'info' : 'success'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['md:excrete:edit']"
              v-if="scope.row.status == '草稿'"
            >拆分</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['md:excrete:remove']"
              v-if="scope.row.status == '草稿'"
            >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh-right"
            @click="handleSplitAgain(scope.row)"
            v-hasPermi="['md:excrete:again']"
            v-if="scope.row.status == '确认'"
          >重新拆分</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品拆分对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品编码" prop="itemCode">
              <el-input v-model="form.itemCode" placeholder="请选择产品编码" readonly>
                <el-button
                  slot="append"
                  @click="handleSelectProduct"
                  icon="el-icon-search"
                  v-if="optType == 'add'">
                </el-button>
              </el-input>
            </el-form-item>
            <ItemSelect ref="itemSelect" @onSelected="onItemSelected" ></ItemSelect>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拆分编码" prop="code">
              <el-input v-model="form.code" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="itemName">
              <el-input v-model="form.itemName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" type="textarea" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="BOM版本" prop="bomName">
              <el-input v-model="form.bomName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="BOM编码" prop="bomCode">
              <el-input v-model="form.bomCode" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="生产数量" prop="productionQuantity">
              <el-input-number
                v-model="form.productionQuantity"
                :step="1"
                :min="1"
                step-strictly
                :max="9999999999"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
                :readonly="optType == 'view'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-divider v-if="optType != 'add'" content-position="center">物料组成</el-divider>

      <el-table :data="excreteLines"
                v-if="optType != 'add'"
                row-key="id"
                :default-expand-all="true"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column label="编码" align="center" prop="itemCode" width="140"/>
        <el-table-column label="名称" align="center" prop="itemName" :show-overflow-tooltip="true"/>
        <el-table-column label="类型" align="center" prop="itemType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_item_product" :value="scope.row.itemType"/>
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" prop="unitOfMeasure" :show-overflow-tooltip="true"/>
        <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true"/>
        <el-table-column label="剩余库存" align="center" prop="quantityOnhand" />
        <el-table-column label="使用量" align="center" prop="used"/>
        <el-table-column label="拆分类型" align="center" prop="excreteType">
          <div class="line-result" slot-scope="scope">
            <el-select
              v-model="scope.row.excreteType"
              placeholder="请选择"
              clearable
              :disabled="optType == 'view'|| scope.row.flag"
              @change="handleChangeExcreteType(scope.row)"
            >
              <el-option
                v-for="dict in dict.type.bom_excrete_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </div>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="optType != 'view'">保 存</el-button>
        <el-button type="success" @click="Finish" v-if="optType == 'update'">确 认</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    重新拆分对话框-->
    <el-dialog title="重新拆分" :visible.sync="openAgain" width="95%" append-to-body>
      <el-form ref="againForm" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品编码" prop="itemCode">
              <el-input v-model="form.itemCode" placeholder="请选择产品编码" readonly>
                <el-button
                  slot="append"
                  @click="handleSelectProduct"
                  icon="el-icon-search"
                  v-if="optType != 'view'">
                </el-button>
              </el-input>
            </el-form-item>
            <ItemSelect ref="itemSelect" @onSelected="onItemSelected" ></ItemSelect>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拆分编码" prop="code">
              <el-input v-model="form.code" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="itemName">
              <el-input v-model="form.itemName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" type="textarea" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="BOM版本" prop="bomName">
              <el-input v-model="form.bomName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="BOM编码" prop="bomCode">
              <el-input v-model="form.bomCode" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="生产数量" prop="productionQuantity">
              <el-input-number
                v-model="form.productionQuantity"
                :step="1"
                :min="1"
                step-strictly
                :max="9999999999"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
                :readonly="optType == 'view'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAgainForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listExcrete,
  getExcrete,
  delExcrete,
  addExcrete,
  updateExcrete,
  againExcrete} from "@/api/mes/md/excrete";
import { listByCode } from "@/api/mes/md/bomgl";
import ItemSelect from "./itemSelect";
import { genCode } from "@/api/system/autocode/rule";

export default {
  name: "Excrete",
  dicts: [ 'bom_excrete_type', 'mes_item_product' ],
  components: {
    ItemSelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品拆分表格数据
      excreteList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openAgain:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemCode: null,
        itemName: null,
        bomCode: null,
        bomName: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemCode: [
          { required: true, message: "产品物料编码不能为空", trigger: "blur" }
        ],
        bomCode: [
          { required: true, message: "BOM编码不能为空", trigger: "change" }
        ],
        code: [
          { required: true, message: "拆分编码不能为空", trigger: "blur" }
        ]
      },
      bomOptions: [],
      optType: null,
      excreteLines: [],
      autoGenFlag: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询产品拆分列表 */
    getList() {
      this.loading = true;
      listExcrete(this.queryParams).then(response => {
        this.excreteList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openAgain = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        bomId: null,
        bomCode: null,
        bomName: null,
        productionQuantity: null,
        used: null,
        excreteType: null,
        status: '草稿',
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.autoGenFlag = false;
      this.excreteLines = [];
      this.resetForm("form");
      this.resetForm("againForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品拆分";
      this.optType = 'add';
      this.handleAutoGenChange(true);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getExcrete(id).then(response => {
        this.form = response.data;
        this.excreteLines = this.handleTree(response.data.excreteItems, 'id', 'parentId');
        this.open = true;
        this.title = "修改产品拆分";
        this.optType = 'update';
      });
    },
    handleSplitAgain(row){
      this.reset();
      const id = row.id || this.ids
      getExcrete(id).then(response => {
        this.form = response.data;
        this.form.status='草稿';
        this.openAgain = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.excreteItems = this.splitTree(this.excreteLines);
            updateExcrete(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExcrete(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitAgainForm(){
      this.$refs["againForm"].validate(valid => {
        if (valid) {
          againExcrete(this.form).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.openAgain = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除产品拆分编号为"' + ids + '"的数据项？')
        .then(function() {
        return delExcrete(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('md/excrete/export', {
        ...this.queryParams
      }, `产品拆分_${new Date().getTime()}.xlsx`)
    },
    handleSelectProduct(){
      this.$refs.itemSelect.showFlag = true;
    },
    onItemSelected(obj){
      if(obj != undefined && obj != null){
        this.form.itemId = obj.itemId;
        this.form.itemCode = obj.itemCode;
        this.form.itemName = obj.itemName;
        this.form.specification = obj.specification;
        this.form.unitOfMeasure = obj.unitOfMeasure;
        this.form.bomCode=obj.bomCode;
        this.form.bomName=obj.bomName;
        this.form.bomId=obj.bomId;
      }
    },
    Finish() {
      let list = this.splitTree(this.excreteLines);
      for (let i = 0; i < list.length; i++) {
        if (list[i].excreteType == null) {
          this.$modal.msgError("请填写拆分类型！");
          return;
        }
      }
      if (this.form.id != null) {
        this.form.status = "确认";
        list.some(item => {
          item.remark = "确认"
        })
        this.form.excreteItems = list;
        updateExcrete(this.form).then(response => {
          this.$modal.msgSuccess("确认成功");
          this.open = false;
          this.getList();
        });
      }
    },
    handleView(row) {
      const id = row.id;
      getExcrete(id).then(response => {
        this.form = response.data;
        this.excreteLines = this.handleTree(response.data.excreteItems, 'id', 'parentId');
        this.open = true;
        this.title = "查看产品拆解";
        this.optType = "view";
      });
    },
    handleAutoGenChange(autoGenFlag){
      if(autoGenFlag){
        genCode('BOM_EXCRETE_CODE').then(response =>{
          this.form.code = response;
        });
      }else{
        this.form.code = null;
      }
    },
    handleChangeExcreteType(row){
      const  children = row.children;
      if(children){
        if(row.excreteType != 3 && row.excreteType){
          children.forEach(item => {
            item.excreteType = row.excreteType;
            item.flag = true;
            this.handleChangeExcreteType(item);
          })
        }else{
          children.forEach(item => {
            item.excreteType = null;
            item.flag = false;
            this.handleChangeExcreteType(item);
          })
        }
      }

    },
    splitTree(treeData,result = []){
      treeData.forEach(item => {
        result.push(item);
        if(item.children && item.children.length > 0){
          this.splitTree(item.children,result);
        }
      })
      return result;
    },

  }
};
</script>
